import datetime

import pandas as pd
import requests
import json
import time

from tools.wrappers import deco_retry
from tools.time_tool import str_to_timestamp, timestamp_to_str


@deco_retry(retry=50, retry_sleep=15)
def get_usdtusd_premium_okex(frequnecy='1d'):
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}
    timestamp_ = str_to_timestamp('2010-01-01') * 1000
    frequency_dict = {'5m': 0, '1h': 1, '1d': 2}
    url = f'https://www.okx.com/v3/c2c/tickers/premiumRate/USDT?t={timestamp_}&interval={frequency_dict[frequnecy]}'
    res = requests.get(url, headers=header, timeout=15)
    df = pd.DataFrame(json.loads(res.content)['data'])
    df['timestamps'] = df['timestamps'] / 1000
    df['datetime'] = df['timestamps'].apply(timestamp_to_str, fmt='%Y-%m-%d %H:%M:%S', tz_str='+0000')
    df['date'] = df['timestamps'].apply(timestamp_to_str, fmt='%Y-%m-%d', tz_str='+0000')
    df.rename(columns={'ratios': 'premium'}, inplace=True)
    return df


@deco_retry(retry=50, retry_sleep=15)
def get_usdtcny_premium_okex():
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}
    timestamp_ = int(time.time() * 1000)
    datetime_ = timestamp_to_str(timestamp_/1000, fmt='%Y-%m-%d %H:%M:%S', tz_str='+0000')
    date_ = timestamp_to_str(timestamp_/1000, fmt='%Y-%m-%d', tz_str='+0000')

    ticker_url = f'https://www.okx.com/v3/c2c/otc-ticker?t={timestamp_}&baseCurrency=USDT&quoteCurrency=CNY'

    res = requests.get(ticker_url, headers=header, timeout=30)
    df_ticker = pd.DataFrame(json.loads(res.content)['data'], index=[0])
    df_ticker.rename(columns={'otcTicker': 'usdtcny'}, inplace=True)
    df_ticker['usdtcny'] = df_ticker['usdtcny'].astype(float)
    df_ticker['timestamp'] = timestamp_
    df_ticker['datetime'] = datetime_
    df_ticker['date'] = date_
    return df_ticker


@deco_retry(retry=50, retry_sleep=15)
def get_usdtcny_orderbook_okex():
    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}
    timestamp_ = int(time.time() * 1000)
    datetime_ = timestamp_to_str(timestamp_ / 1000, fmt='%Y-%m-%d %H:%M:%S', tz_str='+0000')
    date_ = timestamp_to_str(timestamp_ / 1000, fmt='%Y-%m-%d', tz_str='+0000')

    orderbook_url = f'https://www.okx.com/v3/c2c/tradingOrders/books?t={timestamp_}&quoteCurrency=cny&baseCurrency=usdt&side=all' \
                    f'&paymentMethod=all&userType=all&showTrade=false&receivingAds=false&showFollow=false&showAlreadyTraded=false&isAbleFilter=false'

    res = requests.get(orderbook_url, headers=header, timeout=30)
    df_buy = pd.DataFrame(json.loads(res.content)['data']['sell'])
    df_sell = pd.DataFrame(json.loads(res.content)['data']['buy'])
    df_orderbook = pd.concat([df_buy, df_sell], axis=0)
    df_orderbook.rename(columns={'price': 'usdtcny'}, inplace=True)
    df_orderbook['usdtcny'] = df_orderbook['usdtcny'].astype(float)
    df_orderbook['timestamp'] = timestamp_
    df_orderbook['spread'] = (df_buy['price'].astype(float).min() - df_sell['price'].astype(float).max()) / df_sell[
        'price'].astype(float).max()
    df_orderbook['datetime'] = datetime_
    df_orderbook['date'] = date_
    return df_orderbook


@deco_retry(retry=50, retry_sleep=15)
def get_margin_interest_rate_okex():
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'}
    today = datetime.datetime.today().strftime('%Y-%m-%d')
    end = str_to_timestamp(today) * 1000
    url = f'https://www.okx.com/priapi/v5/public/interest-rate-loan-quota?t={end}'
    res = requests.get(url, headers=header, timeout=15)
    datas = json.loads(res.content)
    datas = datas['data'][0]['basic']
    df = pd.DataFrame(datas)
    df['end_date'] = today
    return df

if __name__ == '__main__':
    get_usdtusd_premium_okex('5m')